<?php
namespace Framework\Library\Validator;

use Phalcon\Validation;
use Phalcon\Validation\Validator;
use Phalcon\Validation\ValidatorInterface;
use Phalcon\Validation\Message;

class ArrayValidator extends Validator implements ValidatorInterface
{
    public function validate(Validation $validation, $attribute)
    {
        $arrayParam = $validation->getValue($attribute);

        if (!is_array($arrayParam)) {
            $validation->appendMessage(new Message('Should be an array', $attribute, 'Array'));

            return false;
        }
        if (count($arrayParam) < (int) $this->getOption('min')) {
            $validation->appendMessage(new Message('Array size is too small', $attribute, 'Array'));

            return false;
        }
        if (count($arrayParam) > (int) $this->getOption('max')) {
            $validation->appendMessage(new Message('Array size is too large', $attribute, 'Array'));

            return false;
        }
        if ($this->hasOption('length')) {
            foreach ($arrayParam as $value) {
                if (is_string($value) && mb_strlen($value) > $this->getOption('length')) {
                    $validation->appendMessage(new Message('Array value size is too large', $attribute, 'Array'));

                    return false;
                }
            }
        }

        return true;
    }
}
